home *** CD-ROM | disk | FTP | other *** search
/ Internet Surfer 2.0 / Internet Surfer 2.0 (Wayzata Technology) (1996).iso / pc / text / mac / faqs.222 < prev    next >
Text File  |  1996-02-12  |  28KB  |  794 lines

  1. Frequently Asked Questions (FAQS);faqs.222
  2.  
  3.  
  4.  
  5.         p = (char *)((int *)p + 1);
  6.  
  7.     , or simply
  8.  
  9.         p += sizeof(int);
  10.  
  11.     References: ANSI Sec. 3.3.4, Rationale Sec. 3.3.2.4 p. 43.
  12.  
  13.  
  14. Section 3. Memory Allocation
  15.  
  16. 3.1:    Why doesn't this fragment work?
  17.  
  18.         char *answer;
  19.         printf("Type something:\n");
  20.         gets(answer);
  21.         printf("You typed \"%s\"\n", answer);
  22.  
  23. A:    The pointer variable "answer," which is handed to the gets
  24.     function as the location into which the response should be
  25.     stored, has not been set to point to any valid storage.  That
  26.     is, we cannot say where the pointer "answer" points.  (Since
  27.     local variables are not initialized, and typically contain
  28.     garbage, it is not even guaranteed that "answer" starts out as a
  29.     null pointer.  See question 17.1.)
  30.  
  31.     The simplest way to correct the question-asking program is to
  32.     use a local array, instead of a pointer, and let the compiler
  33.     worry about allocation:
  34.  
  35.         #include <string.h>
  36.  
  37.         char answer[100], *p;
  38.         printf("Type something:\n");
  39.         fgets(answer, 100, stdin);
  40.         if((p = strchr(answer, '\n')) != NULL)
  41.             *p = '\0';
  42.         printf("You typed \"%s\"\n", answer);
  43.  
  44.     Note that this example also uses fgets instead of gets (always a
  45.     good idea), so that the size of the array can be specified, so
  46.     that fgets will not overwrite the end of the array if the user
  47.     types an overly-long line.  (Unfortunately for this example,
  48.     fgets does not automatically delete the trailing \n, as gets
  49.     would.)  It would also be possible to use malloc to allocate the
  50.     answer buffer, and/or to parameterize its size
  51.     (#define ANSWERSIZE 100).
  52.  
  53. 3.2:    I can't get strcat to work.  I tried
  54.  
  55.         char *s1 = "Hello, ";
  56.         char *s2 = "world!";
  57.         char *s3 = strcat(s1, s2);
  58.  
  59.     but I got strange results.
  60.  
  61. A:    Again, the problem is that space for the concatenated result is
  62.     not properly allocated.  C does not provide an automatically-
  63.     managed string type.  C compilers only allocate memory for
  64.     objects explicitly mentioned in the source code (in the case of
  65.     "strings," this includes character arrays and string literals).
  66.     The programmer must arrange (explicitly) for sufficient space
  67.     for the results of run-time operations such as string
  68.     concatenation, typically by declaring arrays, or by calling
  69.     malloc.
  70.  
  71.     strcat performs no allocation; the second string is appended to
  72.     the first one, in place.  Therefore, one fix would be to declare
  73.     the first string as an array with sufficient space:
  74.  
  75.         char s1[20] = "Hello, ";
  76.  
  77.     Since strcat returns the value of its first argument (s1, in
  78.     this case), the s3 variable is superfluous.
  79.  
  80.     Reference: CT&P Sec. 3.2 p. 32.
  81.  
  82. 3.3:    But the man page for strcat says that it takes two char *'s as
  83.     arguments.  How am I supposed to know to allocate things?
  84.  
  85. A:    In general, when using pointers you _always_ have to consider
  86.     memory allocation, at least to make sure that the compiler is
  87.     doing it for you.  If a library routine's documentation does not
  88.     explicitly mention allocation, it is usually the caller's
  89.     problem.
  90.  
  91.     The Synopsis section at the top of a Unix-style man page can be
  92.     misleading.  The code fragments presented there are closer to
  93.     the function definition used by the call's implementor than the
  94.     invocation used by the caller.  In particular, many routines
  95.     which accept pointers (e.g. to structs or strings), are usually
  96.     called with the address of some object (a struct, or an array --
  97.     see questions 2.3 and 2.4.)  Another common example is stat().
  98.  
  99. 3.4:    I have a function that is supposed to return a string, but when
  100.     it returns to its caller, the returned string is garbage.
  101.  
  102. A:    Make sure that the memory to which the function returns a
  103.     pointer is correctly allocated.  The returned pointer should be
  104.     to a statically-allocated buffer, or to a buffer passed in by
  105.     the caller, but _not_ to a local array.  See also question 17.3.
  106.  
  107. 3.5:    You can't use dynamically-allocated memory after you free it,
  108.     can you?
  109.  
  110. A:    No.  Some early man pages for malloc stated that the contents of
  111.     freed memory was "left undisturbed;" this ill-advised guarantee
  112.     was never universal and is not required by ANSI.
  113.  
  114.     Few programmers would use the contents of freed memory
  115.     deliberately, but it is easy to do so accidentally.  Consider
  116.     the following (correct) code for freeing a singly-linked list:
  117.  
  118.         struct list *listp, *nextp;
  119.         for(listp = base; listp != NULL; listp = nextp) {
  120.             nextp = listp->next;
  121.             free((char *)listp);
  122.         }
  123.  
  124.     and notice what would happen if the more-obvious loop iteration
  125.     expression listp = listp->next were used, without the temporary
  126.     nextp pointer.
  127.  
  128.     References: ANSI Rationale Sec. 4.10.3.2 p. 102; CT&P Sec. 7.10
  129.     p. 95.
  130.  
  131. 3.6:    How does free() know how many bytes to free?
  132.  
  133. A:    The malloc/free package remembers the size of each block it
  134.     allocates and returns, so it is not necessary to remind it of
  135.     the size when freeing.
  136.  
  137. 3.7:    So can I query the malloc package to find out how big an
  138.     allocated block is?
  139.  
  140. A:    Not portably.
  141.  
  142. 3.8:    Is it legal to pass a null pointer as the first argument to
  143.     realloc()?  Why would you want to?
  144.  
  145. A:    ANSI C sanctions this usage (and the related realloc(..., 0),
  146.     which frees), but several earlier implementations do not support
  147.     it, so it is not widely portable.  Passing an initially-null
  148.     pointer to realloc can make it easier to write a self-starting
  149.     incremental allocation algorithm.
  150.  
  151.     References: ANSI Sec. 4.10.3.4 .
  152.  
  153. 3.9:    What is the difference between calloc and malloc?  Is it safe to
  154.     use calloc's zero-fill guarantee for pointer and floating-point
  155.     values?  Does free work on memory allocated with calloc, or do
  156.     you need a cfree?
  157.  
  158. A:    calloc(m, n) is essentially equivalent to
  159.  
  160.         p = malloc(m * n);
  161.         memset(p, 0, m * n);
  162.  
  163.     The zero fill is all-bits-zero, and does not therefore guarantee
  164.     useful zero values for pointers (see section 1 of this list) or
  165.     floating-point values.  free can (and should) be used to free
  166.     the memory allocated by calloc.
  167.  
  168.     References: ANSI Secs. 4.10.3 to 4.10.3.2 .
  169.  
  170. 3.10:    What is alloca and why is its use discouraged?
  171.  
  172. A:    alloca allocates memory which is automatically freed when the
  173.     function which called alloca returns.  That is, memory allocated
  174.     with alloca is local to a particular function's "stack frame" or
  175.     context.
  176.  
  177.     alloca cannot be written portably, and is difficult to implement
  178.     on machines without a stack.  Its use is problematical (and the
  179.     obvious implementation on a stack-based machine fails) when its
  180.     return value is passed directly to another function, as in
  181.     fgets(alloca(100), 100, stdin).
  182.  
  183.     For these reasons, alloca cannot be used in programs which must
  184.     be widely portable, no matter how useful it might be.
  185.  
  186.     References: ANSI Rationale Sec. 4.10.3 p. 102.
  187.  
  188.  
  189. Section 4. Expressions
  190.  
  191. 4.1:    Why doesn't this code:
  192.  
  193.         a[i] = i++;
  194.  
  195.     work?
  196.  
  197. A:    The subexpression i++ causes a side effect -- it modifies i's
  198.     value -- which leads to undefined behavior if i is also
  199.     referenced elsewhere in the same expression.
  200.  
  201.     References: ANSI Sec. 3.3 p. 39.
  202.  
  203. 4.2:    Under my compiler, the code
  204.  
  205.         int i = 7;
  206.         printf("%d\n", i++ * i++);
  207.  
  208.     prints 49.  Regardless of the order of evaluation, shouldn't it
  209.     print 56?
  210.  
  211. A:    Although the postincrement and postdecrement operators ++ and --
  212.     perform the operations after yielding the former value, the
  213.     implication of "after" is often misunderstood.  It is _not_
  214.     guaranteed that the operation is performed immediately after
  215.     giving up the previous value and before any other part of the
  216.     expression is evaluated.  It is merely guaranteed that the
  217.     update will be performed sometime before the expression is
  218.     considered "finished" (before the next "sequence point," in ANSI
  219.     C's terminology).  In the example, the compiler chose to
  220.     multiply the previous value by itself and to perform both
  221.     increments afterwards.
  222.  
  223.     The behavior of code which contains multiple, ambiguous side
  224.     effects has always been undefined.  Don't even try to find out
  225.     how your compiler implements such things (contrary to the ill-
  226.     advised exercises in many C textbooks); as K&R wisely point out,
  227.     "if you don't know _how_ they are done on various machines, that
  228.     innocence may help to protect you."
  229.  
  230.     References: K&R I Sec. 2.12 p. 50; K&R II Sec. 2.12 p. 54; ANSI
  231.     Sec. 3.3 p. 39; CT&P Sec. 3.7 p. 47; PCS Sec. 9.5 pp. 120-1.
  232.     (Ignore H&S Sec. 7.12 pp. 190-1, which is obsolete.)
  233.  
  234. 4.3:    But what about the &&, ||, and comma operators?
  235.     I see code like "if((c = getchar()) == EOF || c == '\n')" ...
  236.  
  237. A:    There is a special exception for those operators, (as well as
  238.     ?: ); each of them does imply a sequence point (i.e. left-to-
  239.     right evaluation is guaranteed).  Any book on C should make this
  240.     clear.
  241.  
  242.     References: K&R I Sec. 2.6 p. 38, Secs. A7.11-12 pp. 190-1;
  243.     K&R II Sec. 2.6 p. 41, Secs. A7.14-15 pp. 207-8; ANSI
  244.     Secs. 3.3.13 p. 52, 3.3.14 p. 52, 3.3.15 p. 53, 3.3.17 p. 55,
  245.     CT&P Sec. 3.7 pp. 46-7.
  246.  
  247. 4.4:    If I'm not using the value of the expression, should I use i++
  248.     or ++i to increment a variable?
  249.  
  250. A:    Since the two forms differ only in the value yielded, they are
  251.     entirely equivalent when only their side effect is needed.  Some
  252.     people will tell you that in the old days one form was preferred
  253.     over the other because it utilized a PDP-11 autoincrement
  254.     addressing mode, but those people are confused.
  255.  
  256. 4.5:    Why doesn't the code
  257.  
  258.         int a = 1000, b = 1000;
  259.         long int c = a * b;
  260.  
  261.     work?
  262.  
  263. A:    Under C's integral promotion rules, the multiplication is
  264.     carried out using int arithmetic, and the result may overflow
  265.     and/or be truncated before being assigned to the long int left-
  266.     hand-side.  Use an explicit cast to force long arithmetic:
  267.  
  268.         long int c = (long int)a * b;
  269.  
  270.  
  271. Section 5. ANSI C
  272.  
  273. 5.1:    What is the "ANSI C Standard?"
  274.  
  275. A:    In 1983, the American National Standards Institute commissioned
  276.     a committee, X3J11, to standardize the C language.  After a
  277.     long, arduous process, including several widespread public
  278.     reviews, the committee's work was finally ratified as an
  279.     American National Standard, X3.159-1989, on December 14, 1989,
  280.     and published in the spring of 1990.  For the most part, ANSI C
  281.     standardizes existing practice, with a few additions from C++
  282.     (most notably function prototypes) and support for multinational
  283.     character sets (including the much-lambasted trigraph
  284.     sequences).  The ANSI C standard also formalizes the C run-time
  285.     library support routines.
  286.  
  287.     The published Standard includes a "Rationale," which explains
  288.     many of its decisions, and discusses a number of subtle points,
  289.     including several of those covered here.  (The Rationale is "not
  290.     part of ANSI Standard X3.159-1989, but is included for
  291.     information only.")
  292.  
  293.     The Standard has been adopted as an international standard,
  294.     ISO/IEC 9899:1990, although the sections are numbered
  295.     differently (briefly, ANSI sections 2 through 4 correspond
  296.     roughly to ISO sections 5 through 7), and the Rationale is
  297.     currently not included.
  298.  
  299. 5.2:    How can I get a copy of the Standard?
  300.  
  301. A:    Copies are available from
  302.  
  303.         American National Standards Institute
  304.         11 W. 42nd St., 13th floor
  305.         New York, NY  10036  USA
  306.         (+1) 212 642 4900
  307.  
  308.     or
  309.  
  310.         Global Engineering Documents
  311.         2805 McGaw Avenue
  312.         Irvine, CA  92714  USA
  313.         (+1) 714 261 1455
  314.         (800) 854 7179  (U.S. & Canada)
  315.  
  316.     The cost from ANSI is $50.00, plus $6.00 shipping.  Quantity
  317.     discounts are available.  (Note that ANSI derives revenues to
  318.     support its operations from the sale of printed standards, so
  319.     electronic copies are _not_ available.)
  320.  
  321.     The Rationale, by itself, has been printed by Silicon Press,
  322.     ISBN 0-929306-07-4.
  323.  
  324. 5.3:    Does anyone have a tool for converting old-style C programs to
  325.     ANSI C, or vice versa, or for automatically generating
  326.     prototypes?
  327.  
  328. A:    Two programs, protoize and unprotoize, convert back and forth
  329.     between prototyped and "old style" function definitions and
  330.     declarations.  (These programs do _not_ handle full-blown
  331.     translation between "Classic" C and ANSI C.)  These programs
  332.     exist as patches to the FSF GNU C compiler, gcc.  Look for the
  333.     file protoize-1.39.0.5.Z in pub/gnu at prep.ai.mit.edu
  334.     (18.71.0.38), or at several other FSF archive sites.
  335.  
  336.     The unproto program (/pub/unix/unproto4.shar.Z on
  337.     ftp.win.tue.nl) is a filter which sits between the preprocessor
  338.     and the next compiler pass, converting most of ANSI C to
  339.     traditional C on-the-fly.
  340.  
  341.     The GNU GhostScript package comes with a little program called
  342.     ansi2knr.
  343.  
  344.     Several prototype generators exist, many as modifications to
  345.     lint.  Version 3 of CPROTO was posted to comp.sources.misc in
  346.     March, 1992.  (See also question 17.8.)
  347.  
  348. 5.4:    I'm trying to use the ANSI "stringizing" preprocessing operator
  349.     # to insert the value of a symbolic constant into a message, but
  350.     it keeps stringizing the macro's name rather than its value.
  351.  
  352. A:    You must use something like the following two-step procedure to
  353.     force the macro to be expanded as well as stringized:
  354.  
  355.         #define str(x) #x
  356.         #define xstr(x) str(x)
  357.         #define OP plus
  358.         char *opname = xstr(OP);
  359.  
  360.     This sets opname to "plus" rather than "OP".
  361.  
  362.     An equivalent circumlocution is necessary with the token-pasting
  363.     operator ## when the values (rather than the names) of two
  364.     macros are to be concatenated.
  365.  
  366.     References: ANSI Sec. 3.8.3.2, Sec. 3.8.3.5 example p. 93.
  367.  
  368. 5.5:    What's the difference between "char const *p" and
  369.     "char * const p"?
  370.  
  371. A:    "char const *p" is a pointer to a constant character (you can't
  372.     change the character); "char * const p" is a constant pointer to
  373.     a (variable) character (i.e. you can't change the pointer).
  374.     (Read these "inside out" to understand them.  See question
  375.     10.3.)
  376.  
  377.     References: ANSI Sec. 3.5.4.1 .
  378.  
  379. 5.6:    My ANSI compiler complains about a mismatch when it sees
  380.  
  381.         extern int func(float);
  382.  
  383.         int func(x)
  384.         float x;
  385.         {...
  386.  
  387. A:    You have mixed the new-style prototype declaration
  388.     "extern int func(float);" with the old-style definition
  389.     "int func(x) float x;".  Old C (and ANSI C, in the absence of
  390.     prototypes, and in variable-length argument lists) "widens"
  391.     certain arguments when they are passed to functions.  floats
  392.     are promoted to double, and characters and short integers are
  393.     promoted to integers.  (The values are automatically coerced
  394.     back to the corresponding narrower types within the body of the
  395.     called function, if they are declared that way there.)
  396.  
  397.     The problem can be fixed either by using new-style syntax
  398.     consistently in the definition:
  399.  
  400.         int func(float x) { ... }
  401.  
  402.     or by changing the new-style prototype declaration to match the
  403.     old-style definition:
  404.  
  405.         extern int func(double);
  406.  
  407.     (In this case, it would be clearest to change the old-style
  408.     definition to use double as well, as long as the address of that
  409.     parameter is not taken.)
  410.  
  411.     It may also be safer to avoid "narrow" (char, short int, and
  412.     float) function arguments and return types.
  413.  
  414.     References: ANSI Sec. 3.3.2.2 .
  415.  
  416. 5.7:    I'm getting strange syntax errors inside code which I've
  417.     #ifdeffed out.
  418.  
  419. A:    Under ANSI C, the text inside a "turned off" #if, #ifdef, or
  420.     #ifndef must still consist of "valid preprocessing tokens."
  421.     This means that there must be no unterminated comments or quotes
  422.     (note particularly that an apostrophe within a contracted word
  423.     could look like the beginning of a character constant), and no
  424.     newlines inside quotes.  Therefore, natural-language comments
  425.     and pseudocode should always be written between the "official"
  426.     comment delimiters /* and */.  (But see also question 17.10, and
  427.     6.7.)
  428.  
  429.     References: ANSI Sec. 2.1.1.2 p. 6, Sec. 3.1 p. 19 line 37.
  430.  
  431. 5.8:    Can I declare main as void, to shut off these annoying "main
  432.     returns no value" messages?  (I'm calling exit(), so main
  433.     doesn't return.)
  434.  
  435. A:    No.  main must be declared as returning an int, and as taking
  436.     either zero or two arguments (of the appropriate type).  If
  437.     you're calling exit() but still getting warnings, you'll have to
  438.     insert a redundant return statement (or use some kind of
  439.     "notreached" directive, if available).
  440.  
  441.     References: ANSI Sec. 2.1.2.2.1 pp. 7-8.
  442.  
  443. 5.9:    Why does the ANSI Standard not guarantee more than six monocase
  444.     characters of external identifier significance?
  445.  
  446. A:    The problem is older linkers which are neither under the control
  447.     of the ANSI standard nor the C compiler developers on the
  448.     systems which have them.  The limitation is only that
  449.     identifiers be _significant_ in the first six characters, not
  450.     that they be restricted to six characters in length.  This
  451.     limitation is annoying, but certainly not unbearable, and is
  452.     marked in the Standard as "obsolescent," i.e. a future revision
  453.     will likely relax it.
  454.  
  455.     This concession to current, restrictive linkers really had to be
  456.     made, no matter how vehemently some people oppose it.  (The
  457.     Rationale notes that its retention was "most painful.")  If you
  458.     disagree, or have thought of a trick by which a compiler
  459.     burdened with a restrictive linker could present the C
  460.     programmer with the appearance of more significance in external
  461.     identifiers, read the excellently-worded section 3.1.2 in the
  462.     X3.159 Rationale (see question 5.1), which discusses several
  463.     such schemes and explains why they could not be mandated.
  464.  
  465.     References: ANSI Sec. 3.1.2 p. 21, Sec. 3.9.1 p. 96, Rationale
  466.     Sec. 3.1.2 pp. 19-21.
  467.  
  468. 5.10:    What is the difference between memcpy and memmove?
  469.  
  470. A:    memmove offers guaranteed behavior if the source and destination
  471.     arguments overlap.  memcpy makes no such guarantee, and may
  472.     therefore be more efficiently implementable.  When in doubt,
  473.     it's safer to use memmove.
  474.  
  475.     References: ANSI Secs. 4.11.2.1, 4.11.2.2, Rationale
  476.     Sec. 4.11.2 .
  477.  
  478. 5.11:    My compiler is rejecting the simplest possible test programs,
  479.     with all kinds of syntax errors.
  480.  
  481. A:    Perhaps it is a pre-ANSI compiler, unable to accept function
  482.     prototypes and the like.
  483.  
  484. 5.12:    Why won't the Frobozz Magic C Compiler, which claims to be ANSI
  485.     compliant, accept this code?  I know that the code is ANSI,
  486.     because gcc accepts it.
  487.  
  488. A:    Most compilers support a few non-Standard extensions, gcc more
  489.     so than most.  Are you sure that the code being rejected doesn't
  490.     rely on such an extension?  It is usually a bad idea to perform
  491.     experiments with a particular compiler to determine properties
  492.     of a language; the applicable standard may permit variations, or
  493.     the compiler may be wrong.
  494.  
  495. 5.13:    What are #pragmas and what are they good for?
  496.  
  497. A:    The #pragma directive provides a single, well-defined "escape
  498.     hatch" which can be used for all sorts of implementation-
  499.     specific controls and extensions: source listing control,
  500.     structure packing, warning suppression (like the old lint
  501.     /* NOTREACHED */ comments), etc.
  502.  
  503.     References: ANSI Sec. 3.8.6 .
  504.  
  505.  
  506. Section 6. C Preprocessor
  507.  
  508. 6.1:    How can I write a generic macro to swap two values?
  509.  
  510. A:    There is no good answer to this question.  If the values are
  511.     integers, a well-known trick using exclusive-OR could perhaps be
  512.     used, but it will not work for floating-point values or
  513.     pointers, or if the two values are the same variable (and the
  514.     "obvious" supercompressed implementation for integral types
  515.     a^=b^=a^=b is in fact illegal due to multiple side-effects,
  516.     and...).  If the macro is intended to be used on values of
  517.     arbitrary type (the usual goal), it cannot use a temporary,
  518.     since it does not know what type of temporary it needs, and
  519.     standard C does not provide a typeof operator.
  520.  
  521.     The best all-around solution is probably to forget about using a
  522.     macro, unless you're willing to pass in the type as a third
  523.     argument.
  524.  
  525. 6.2:    I have some old code that tries to construct identifiers with a
  526.     macro like
  527.  
  528.         #define Paste(a, b) a/**/b
  529.  
  530.     but it doesn't work any more.
  531.  
  532. A:    That comments disappeared entirely and could therefore be used
  533.     for token pasting was an undocumented feature of some early
  534.     preprocessor implementations, notably Reiser's.  ANSI affirms
  535.     (as did K&R) that comments are replaced with white space.
  536.     However, since the need for pasting tokens was demonstrated and
  537.     real, ANSI introduced a well-defined token-pasting operator, ##,
  538.     which can be used like this:
  539.  
  540.         #define Paste(a, b) a##b
  541.  
  542.     (See also question 5.4.)
  543.  
  544.     Reference: ANSI Sec. 3.8.3.3 p. 91, Rationale pp. 66-7.
  545.  
  546. 6.3:    What's the best way to write a multi-statement cpp macro?
  547.  
  548. A:    The usual goal is to write a macro that can be invoked as if it
  549.     were a single function-call statement.  This means that the
  550.     "caller" will be supplying the final semicolon, so the macro
  551.     body should not.  The macro body cannot be a simple brace-
  552.     delineated compound statement, because syntax errors would
  553.     result if it were invoked (apparently as a single statement, but
  554.     with a resultant extra semicolon) as the if branch of an if/else
  555.     statement with an explicit else clause.
  556.  
  557.     The traditional solution is to use
  558.  
  559.         #define Func() do { \
  560.             /* declarations */ \
  561.             stmt1; \
  562.             stmt2; \
  563.             /* ... */ \
  564.             } while(0)    /* (no trailing ; ) */
  565.  
  566.     When the "caller" appends a semicolon, this expansion becomes a
  567.     single statement regardless of context.  (An optimizing compiler
  568.     will remove any "dead" tests or branches on the constant
  569.     condition 0, although lint may complain.)
  570.  
  571.     If all of the statements in the intended macro are simple
  572.     expressions, with no declarations or loops, another technique is
  573.     to write a single, parenthesized expression using one or more
  574.     comma operators.  (See the example under question 6.8 below.
  575.     This technique also allows a value to be "returned.")
  576.  
  577.     Reference: CT&P Sec. 6.3 pp. 82-3.
  578.  
  579. 6.4:    Is it acceptable for one header file to #include another?
  580.  
  581. A:    There has been considerable debate surrounding this question.
  582.     Many people believe that "nested #include files" are to be
  583.     avoided: the prestigious Indian Hill Style Guide (see question
  584.     14.3) disparages them; they can make it harder to find relevant
  585.     definitions; they can lead to multiple-declaration errors if a
  586.     file is #included twice; and they make manual Makefile
  587.     maintenance very difficult.  On the other hand, they make it
  588.     possible to use header files in a modular way (a header file
  589.     #includes what it needs itself, rather than requiring each
  590.     #includer to do so, a requirement that can lead to intractable
  591.     headaches); a tool like grep (or a tags file) makes it easy to
  592.     find definitions no matter where they are; a popular trick:
  593.  
  594.         #ifndef HEADER_FILE_NAME
  595.         #define HEADER_FILE_NAME
  596.         ...header file contents...
  597.         #endif
  598.  
  599.     makes a header file "idempotent" so that it can safely be
  600.     #included multiple times; and automated Makefile maintenance
  601.     tools (which are a virtual necessity in large projects anyway)
  602.     handle dependency generation in the face of nested #include
  603.     files easily.
  604.  
  605. 6.5:    Does the sizeof operator work in preprocessor #if directives?
  606.  
  607. A:    No.  Preprocessing happens during an earlier pass of
  608.     compilation, before type names have been parsed.  Consider using
  609.     the predefined constants in ANSI's <limits.h>, or a "configure"
  610.     script, instead.
  611.  
  612.     References: ANSI Sec. 2.1.1.2 pp. 6-7, Sec. 3.8.1 p. 87
  613.     footnote 83.
  614.  
  615. 6.6:    How can I use a preprocessor #if expression to tell if a machine
  616.     is big-endian or little-endian?
  617.  
  618. A:    You probably can't.  (Preprocessor arithmetic uses only long
  619.     ints, and there is no concept of addressing.)  Are you sure you
  620.     need to know the machine's endianness explicitly?  Usually it's
  621.     better to write code which doesn't care.
  622.  
  623. 6.7:    I've got this tricky processing I want to do at compile time and
  624.     I can't figure out a way to get cpp to do it.
  625.  
  626. A:    cpp is not intended as a general-purpose preprocessor.  Rather
  627.     than forcing it to do something inappropriate, consider writing
  628.     your own little special-purpose preprocessing tool, instead.
  629.     You can easily get a utility like make(1) to run it for you
  630.     automatically.
  631.  
  632.     If you are trying to preprocess something other than C, consider
  633.     using a general-purpose preprocessor (such as m4).
  634.  
  635. 6.8:    How can I write a cpp macro which takes a variable number of
  636.     arguments?
  637.  
  638. A:    One popular trick is to define the macro with a single argument,
  639.     and call it with a double set of parentheses, which appear to
  640.     the preprocessor to indicate a single argument:
  641.  
  642.         #define DEBUG(args) (printf("DEBUG: "), printf args)
  643.  
  644.         if(n != 0) DEBUG(("n is %d\n", n));
  645.  
  646.     The obvious disadvantage is that the caller must always remember
  647.     to use the extra parentheses.  (It is often better to use a
  648.     bona-fide function, which can take a variable number of
  649.     arguments in a well-defined way.  See questions 7.1 and 7.2
  650.     below.)
  651.  
  652.  
  653. Section 7. Variable-Length Argument Lists
  654.  
  655. 7.1:    How can I write a function that takes a variable number of
  656.     arguments?
  657.  
  658. A:    Use the <stdarg.h> header (or, if you must, the older
  659.     <varargs.h>).
  660.  
  661.     Here is a function which concatenates an arbitrary number of
  662.     strings into malloc'ed memory:
  663.  
  664.         #include <stdlib.h>        /* for malloc, NULL, size_t */
  665.         #include <stdarg.h>        /* for va_ stuff */
  666.         #include <string.h>        /* for strcat et al */
  667.  
  668.         char *vstrcat(char *first, ...)
  669.         {
  670.             size_t len = 0;
  671.             char *retbuf;
  672.             va_list argp;
  673.             char *p;
  674.  
  675.             if(first == NULL)
  676.                 return NULL;
  677.  
  678.             len = strlen(first);
  679.  
  680.             va_start(argp, first);
  681.  
  682.             while((p = va_arg(argp, char *)) != NULL)
  683.                 len += strlen(p);
  684.  
  685.             va_end(argp);
  686.  
  687.             retbuf = malloc(len + 1);    /* +1 for trailing \0 */
  688.  
  689.             if(retbuf == NULL)
  690.                 return NULL;        /* error */
  691.  
  692.             (void)strcpy(retbuf, first);
  693.  
  694.             va_start(argp, first);
  695.  
  696.             while((p = va_arg(argp, char *)) != NULL)
  697.                 (void)strcat(retbuf, p);
  698.  
  699.             va_end(argp);
  700.  
  701.             return retbuf;
  702.         }
  703.  
  704.     Usage is something like
  705.  
  706.         char *str = vstrcat("Hello, ", "world!", (char *)NULL);
  707.  
  708.     Note the cast on the last argument.  (Also note that the caller
  709.     must free the returned, malloc'ed storage.)
  710.  
  711.     Under a pre-ANSI compiler, rewrite the function definition
  712.     without a prototype ("char *vstrcat(first) char *first; {"),
  713.     include <stdio.h> rather than <stdlib.h>, add "extern
  714.     char *malloc();", and use int instead of size_t.  You may also
  715.     have to delete the (void) casts, and use the older varargs
  716.     package instead of stdarg.  See the next question for hints.
  717.  
  718.     Remember that in variable-length argument lists, function
  719.     prototypes do not supply parameter type information; therefore,
  720.     default argument promotions apply (see question 5.6), and null
  721.     pointer arguments must be typed explicitly (see question 1.2).
  722.  
  723.     References: K&R II Sec. 7.3 p. 155, Sec. B7 p. 254; H&S
  724.     Sec. 13.4 pp. 286-9; ANSI Secs. 4.8 through 4.8.1.3 .
  725.  
  726. 7.2:    How can I write a function that takes a format string and a
  727.     variable number of arguments, like printf, and passes them to
  728.     printf to do most of the work?
  729.  
  730. A:    Use vprintf, vfprintf, or vsprintf.
  731.  
  732.     Here is an "error" routine which prints an error message,
  733.     preceded by the string "error: " and terminated with a newline:
  734.  
  735.         #include <stdio.h>
  736.         #include <stdarg.h>
  737.  
  738.         void
  739.         error(char *fmt, ...)
  740.         {
  741.             va_list argp;
  742.             fprintf(stderr, "error: ");
  743.             va_start(argp, fmt);
  744.             vfprintf(stderr, fmt, argp);
  745.             va_end(argp);
  746.             fprintf(stderr, "\n");
  747.         }
  748.  
  749.     To use the older <varargs.h> package, instead of <stdarg.h>,
  750.     change the function header to:
  751.  
  752.         void error(va_alist)
  753.         va_dcl
  754.         {
  755.             char *fmt;
  756.  
  757.     change the va_start line to
  758.  
  759.         va_start(argp);
  760.  
  761.     and add the line
  762.  
  763.         fmt = va_arg(argp, char *);
  764.  
  765.     between the calls to va_start and vfprintf.  (Note that there is
  766.     no semicolon after va_dcl.)
  767.  
  768.     References: K&R II Sec. 8.3 p. 174, Sec. B1.2 p. 245; H&S
  769.     Sec. 17.12 p. 337; ANSI Secs. 4.9.6.7, 4.9.6.8, 4.9.6.9 .
  770.  
  771. 7.3:    How can I discover how many arguments a function was actually
  772.     called with?
  773.  
  774. A:    This information is not available to a portable program.  Some
  775.     systems provide a nonstandard nargs() function, but its use is
  776.     questionable, since it typically returns the number of words
  777.     passed, not the number of arguments.  (Floating point values and
  778.     structures are usually passed as several words.)
  779.  
  780.     Any function which takes a variable number of arguments must be
  781.     able to determine from the arguments themselves how many of them
  782.     there are.  printf-like functions do this by looking for
  783.     formatting specifiers (%d and the like) in the format string
  784.     (which is why these functions fail badly if the format string
  785.     does not match the argument list).  Another common technique
  786.     (useful when the arguments are all of the same type) is to use a
  787.     sentinel value (often 0, -1, or an appropriately-cast null
  788.     pointer) at the end of the list (see the execl and vstrcat
  789.     examples under questions 1.2 and 7.1 above).
  790.  
  791. 7.4:    How can I write a function which takes a variable number of
  792.     arguments and passes them to some other function (which takes a
  793.     variable number of arguments)?
  794.